package news.yp.newsproject.utils;

import android.content.Context;
import android.util.Log;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

/**
 * okhttp下载器
 */
public class DownLoadUtils {

    private static volatile DownLoadUtils mInstance;
    private OkHttpClient okHttpClient;
    private Context mContext;

    private DownLoadUtils(Context mContext) {
        if (mInstance != null) {
            throw new RuntimeException("DownLoadUtils can create only one instacne");
        }
        okHttpClient = new OkHttpClient();
    }

    public static DownLoadUtils create(Context mContext) {
        if (mInstance == null) {
            synchronized (DownLoadUtils.class) {
                if (mInstance == null) {
                    mInstance = new DownLoadUtils(mContext);
                }
            }
        }
        return mInstance;
    }

    public void startDownload(final String url, final String fileSavepath, final DownLoadListener listener) {
        Log.e("TAG", "请求的url" + url);

        Request request = new Request.Builder()
                .url(url)
                .build();

        okHttpClient.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                listener.onFail(e);
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                InputStream inputStream = null;
                byte[] buf = new byte[2048];
                int len = 0;
                FileOutputStream fos = null;

                //存储下载文件的目录
                File dir = new File(fileSavepath);
                if (!dir.exists()) {
                    dir.mkdir();
                }
                File file = new File(dir, getFileName(url));

                try {
                    inputStream = response.body().byteStream();
                    long total = response.body().contentLength();
                    Log.e("TAG", "服务器返回的长度contentLength---" + total);
                    fos = new FileOutputStream(file);
                    long sum = 0;
                    while ((len = inputStream.read(buf)) != -1) {
                        fos.write(buf, 0, len);
                        sum += len;
                        int progress = (int) (sum * 1.0f / total * 100);
                        //下载进度更新
                        listener.onProgress(progress);
                    }
                    fos.flush();
                    //下载完成
                    listener.onSuccess(file);
                } catch (Exception e) {
                    listener.onFail(e);
                } finally {
                    try {
                        if (inputStream != null) {
                            inputStream.close();
                        }
                        if (fos != null) {
                            fos.close();
                        }
                    } catch (IOException e) {

                    }
                }
            }
        });
    }

    public interface DownLoadListener {
        //下载成功之后的文件
        void onSuccess(File file);

        void onFail(Exception e);

        //下载进度
        void onProgress(int progress);
    }

    public String getFileName(String fileName) {
        String[] split = fileName.split("&");
        return split[split.length - 1];
    }
}
